package at.stefanirndorfer.openaltest.graphics;

import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.glClear;

import java.io.FileNotFoundException;

import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;

import at.fhooe.stefanirndorfer.engine.game.Game;
import at.stefanirndorfer.openaltest.entity.EntityManager;
import at.stefanirndorfer.openaltest.input.InputManager;
import at.stefanirndorfer.openaltest.input.KeyInputListener;
import at.stefanirndorfer.openaltest.time.Timer;

public class Window implements KeyInputListener{

	private static final int FRAMERATE = 60;
	private String id;
	private int width;
	private int height;
	private String title;
	private InputManager im;
	private RenderManager rm;
	private Timer timer;
	private EntityManager em;
	
	public Window(int width, int height, String title,EntityManager em, InputManager im, RenderManager rm, Timer timer){
		id = this.getClass().getSimpleName() + System.nanoTime();
		
		this.width = width;
		this.height = height;
		this.title = title;
		this.im = im;
		this.rm = rm;
		this.em = em;
		this.timer = timer;
		setUpKeyInputListener();
	}
	
	public void openWindow() throws LWJGLException, FileNotFoundException{
		Display.setDisplayMode(new DisplayMode(width, height));
		Display.setTitle(title);
		Display.setInitialBackground(1.0f, 1.0f, 1.0f);
		Display.create();
		
		//initialisation of openGL
		Graphics_Utils.initializeOpenGL(width, height);
		
		timer.getDelta(); // call once before loop to initialise lastFrame
		int delta = 0;
		
		/** transfers the coordinates origin to the center*/
		
		
		while(!Display.isCloseRequested()){
			
			
			
			delta = timer.getDelta();

			//Input
			
			//process mouse input
			im.dispatchMouseEvents();
			
			
			//process keyboard input
			while (Keyboard.next()){
				im.dispatchKeyEvents(Keyboard.getEventKey(), Keyboard.getEventKeyState());
			}
			
			//upadate Entities
			em.updateAll(delta);
			
			//Render
			glClear(GL_COLOR_BUFFER_BIT);
			// if 3d
			//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			
			
			rm.renderAll();
			
			Display.setTitle(timer.updateFPS());
			Display.update();
			Display.sync(FRAMERATE);
		}
		
		endProgram();
	}

	

	
	private void endProgram() {
	    Game.getInstance().getSoundManager().cleanUp();
		Display.destroy();
		System.exit(0);
	}

	

	@Override
	public void setUpKeyInputListener() {
		im.addKeyListener(this);
		
	}

	@Override
	public void tearDownKeyInputListener(KeyInputListener il) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void processKeyInput(int eventKey, boolean keyDown) {
		if(eventKey == Keyboard.KEY_ESCAPE && keyDown){
			endProgram();
		}
		
	}

	@Override
	public String getId() {
		return id;
	}

	public int getWindowWidth() {
		return width;
	}

	public int getWindwoHeight() {
		return height;
	}
	
}
